﻿package game.ui {
	import game.objects.GameObject;
	import flash.events.Event;
	import flash.display.MovieClip;
	
	public class Loading extends GameObject {
		
		public var percent:int		= 0;
		public var c_percent:int	= 0;
		public var current_path:int = 0;
		public var max_path:int		= 3; //максимальное кол-во частей лоадера, парсинг сети + загрузка библиотек + логин
		
		private var minX:Number		= 0;
		private var maxX:Number		= 0;
		
		private var scroll:MovieClip;
		private var text:Text;
		
		public function Loading():void {
			this.addEventListener(Event.ADDED_TO_STAGE,	added);
			this.addEventListener(Event.REMOVED_FROM_STAGE,	removed);
			
			scroll = getChildByName('bar') as MovieClip;
			maxX = scroll.x;
			minX = -451;
		}
		
		private function removed(event:Event):void {
			this.removeEventListener	( Event.ENTER_FRAME,	enterFrame );
			
		}
		
		private function added(event:Event):void {
			
			text = new Text;
			text.setFormat ('color', 0xffffff);
			text.setFormat ('size', 15);
			addChild(text);
			
			this.addEventListener	( Event.ENTER_FRAME, enterFrame );
			
		}
		
		
		private function enterFrame(event:Event):void {
			if (c_percent<percent) {
				c_percent ++;
				text.set('loading... %percent%%', {percent: c_percent}, false);
				text.x = (stage.stageWidth - text.width)/2;
				text.y = 70;
				scroll.x = minX + ((maxX - minX)*c_percent/100);
			} else if (c_percent==100) {
				hide();
			}
		}
		
		
		public function next():void {
			if (current_path==max_path) {
				hide();
			} else {
				current_path ++;
				progress(0);
			}
		}
		
		private function hide():void {
			//this.cacheAsBitmap = true;
			//animate('alpha', 1, 0, 3, remove);
			remove(null);
		}
		
		private function remove(event):void {
			try {
				this.parent.removeChild(this);
			} catch (e:Error) {
				
			}
		}
		
		public function progress(value:Number):void {
			percent = Math.round((current_path / max_path + value / max_path)*100);
		}
		
	}
}